package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.leyou.common.exception.pojo.LyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;

    @Autowired
    private WXPayConfigImpl payConfig;

    public String getCodeUrl(Long orderId, Long totalFee){
        log.info("【获取微信支付url工具类】开始执行！");
        // 请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "乐优商城");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", totalFee.toString());
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", payConfig.getNotifyUrl());
        data.put("trade_type", payConfig.getPayType());  // 此处指定为扫码支付

        try {
            Map<String, String> resp = wxPay.unifiedOrder(data); //就是为了获取支付链接
            //校验返回结果是否正确
            checkResp(resp);
            //返回codeUrl
            return resp.get("code_url");
        } catch (Exception e) {
            log.error("【获取微信支付url工具类】异常！");
            throw new LyException(501, e.getMessage());
        }
    }

    public void checkResp(Map<String, String> resp) {
        if(!StringUtils.equals(resp.get("return_code"), "SUCCESS")){
            log.error("【获取微信支付url工具类】网络通信异常！异常信息为：{}", resp.get("return_msg"));
            throw new LyException(501, "【获取微信支付url工具类】网络通信异常！");
        }
        if(!StringUtils.equals(resp.get("result_code"), "SUCCESS")){
            log.error("【获取微信支付url工具类】业务异常！异常信息为：{}", resp.get("err_code_des"));
            throw new LyException(501, "【获取微信支付url工具类】业务异常！");
        }
    }

}
